package top.goldenyear.porpoise.infra.log.util;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.jfinal.kit.Kv;
import com.jfinal.template.Engine;
import com.jfinal.template.Template;

/**
 * 操作日志工具类 目前主要的作用，是提供给业务代码，记录操作明细和拓展字段
 *
 * @author Airhead
 */
public class OperateLogUtils {

  private static final ThreadLocal<Kv> THREAD_LOCAL = new TransmittableThreadLocal<>();

  private static final Engine ENGINE = Engine.create("auditLog");

  public static String getContent() {
    return get().getAs("content");
  }

  public static void setContent(String content) {
    get().set("content", content);
  }

  public static void addExt(String key, Object value) {
    Kv ext = get().getAs("ext");
    if (ext == null) {
      ext = Kv.create();
    }
    ext.set(key, value);
  }

  public static Kv getExt() {
    return get().getAs("ext");
  }

  public static void set(Kv kv) {
    THREAD_LOCAL.set(kv);
  }

  public static Kv get() {
    Kv kv = THREAD_LOCAL.get();
    if (kv == null) {
      kv = Kv.create();
      set(kv);
      return kv;
    }

    return kv;
  }

  /**
   * 对AuditLog.operation进行模版化输出
   *
   * @param operation
   * @return
   */
  public static String render(String operation) {
    Template template = ENGINE.getTemplateByString(operation, true);
    return template.renderToString(get());
  }
}
